/*
 *   Copyright 2006 Wei Lian <lianwei3@gmail.com>
 *
 *   This program is free software; you can redistribute it and/or
 *   modify it under the terms of the GNU General Public License
 *   as published by the Free Software Foundation; either version 2
 *   of the License, or (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */
#include "header.h"
#include "fork.h"
#include "socket.h"
#include "loadsave.h"

extern GtkLabel *label_player;
extern GtkWidget *button_attach;
extern pid_t pid_player;
extern char new_url[];
extern gboolean tracing;
extern int detach_flag;
extern GtkWidget *entry_status;
extern GtkTextBuffer *text_buf;
extern GtkAdjustment *adj_text;


inline void
text_buffer_insert (GtkTextBuffer * buf, const char *str)
{
  GtkTextIter cursor;
  gtk_text_buffer_get_end_iter (buf, &cursor);
  gtk_text_buffer_insert (buf, &cursor, str, -1);
}


inline void
getdata (pid_t traced_process, long addr, char *str, int len)
{
  char *laddr;
  int i, j;
  union u
  {
    long val;
    char chars[sizeof (long)];
  } data;
  i = 0;
  j = len / sizeof (long);
  laddr = str;
  while (i < j)
    {
      if ((data.val = ptrace ((enum __ptrace_request) PTRACE_PEEKDATA,
			      traced_process, addr + i * 4, NULL)) == -1)
	{
	  perror ("ptrace peekdata 1");
	  detach_flag = 1;
	}
      memcpy (laddr, data.chars, sizeof (long));
      ++i;
      laddr += sizeof (long);
    }
  j = len % sizeof (long);
  if (j != 0)
    {
      if ((data.val = ptrace ((enum __ptrace_request) PTRACE_PEEKDATA,
			      traced_process, addr + i * 4, NULL)) == -1)
	{
	  perror ("ptrace peekdata 2");
	  detach_flag = 1;
	}
      memcpy (laddr, data.chars, j);
    }
  str[len] = '\0';
}

inline void
processSignal (int result, int status, pid_t traced_process)
{
  long orig_eax;
  long params[2];
  static int toggle = 0;

  ////status=1407(5):Trace Trap(process), 4991(19):Stop(continue), 3455(13):Broken Pipe(ptrace_continue)

  if (WIFEXITED (status))	// || WIFSIGNALED (status))
    {
      if (result == pid_player)
	{
	  pid_player = -1;
	  if (detach_flag != 2)
	    {
	      ///change color of label_player
	      GdkColor color;
	      gdk_color_parse ("black", &color);
	      gtk_widget_modify_fg (GTK_WIDGET (label_player),
				    GTK_STATE_ACTIVE, &color);
	    }
	}
    }
  else if (WIFSTOPPED (status))
    {
      if (detach_flag == 0)	///attached
	{
	  int sig = WSTOPSIG (status);
	  switch (sig)
	    {
	    case SIGTRAP:
	      if ((orig_eax = ptrace ((enum __ptrace_request) PTRACE_PEEKUSER,
				      traced_process, 4 * ORIG_EAX,
				      NULL)) == -1)
		perror ("ptrace peekuser orig_eax");
	      if (orig_eax == SYS_write)
		{
		  if (toggle == 0)
		    {
		      toggle = 1;

		      if ((params[0] =
			   ptrace ((enum __ptrace_request) PTRACE_PEEKUSER,
				   traced_process, 4 * ECX, NULL)) == -1)
			perror ("ptrace peekuser ecx");
		      if ((params[1] =
			   ptrace ((enum __ptrace_request) PTRACE_PEEKUSER,
				   traced_process, 4 * EDX, NULL)) == -1)
			perror ("ptrace peekuser edx");

		      char *str =
			(char *) malloc ((params[1] + 1) * sizeof (char));
		      getdata (traced_process, params[0], str, params[1]);

		      char *strtok;
		      if ((strtok = strstr (str, "@LM_")) != 0)
			{
			  if (strstr (strstr (str, "@LM_") + 1, "@") != 0)
			    strtok =
			      strstr (strstr (str, "@LM_") + 1, "@") + 1;
			  text_buffer_insert (text_buf, strtok);
			  gtk_adjustment_set_value (adj_text,
						    adj_text->upper -
						    adj_text->page_size + 15);

			  if (strstr (str, "@try to connect...") != 0)
			    gtk_entry_set_text (GTK_ENTRY (entry_status),
						"try to connect...");

			  if (strstr (str, "@Resource Not Found!") != 0)
			    gtk_entry_set_text (GTK_ENTRY (entry_status),
						"Resource Not Found!");
			}
		      else if (strstr (str, "http:") != 0)
			{
			  char *utf8_text;
			  utf8_text =
			    g_locale_to_utf8 (str, strlen (str), NULL, NULL,
					      NULL);
			  text_buffer_insert (text_buf, utf8_text);
			  gtk_adjustment_set_value (adj_text,
						    adj_text->upper -
						    adj_text->page_size +
						    15 * 6);

			  char *strtok_buf;
			  ////strtok_r will change data!
			  strtok =
			    strtok_r (strstr (str, "http:"), "\">",
				      &strtok_buf);
			  strcpy (new_url, strtok);
			  strtok =
			    strtok_r (strstr (utf8_text, "<TITLE>") + 7, "<",
				      &strtok_buf);
			  gtk_entry_set_text (GTK_ENTRY (entry_status),
					      strtok);
			}
		      free (str);
		    }
		  else
		    {
		      toggle = 0;
		    }
		}
	      if (ptrace ((enum __ptrace_request) PTRACE_SYSCALL,
			  traced_process, NULL, NULL) == -1)
		perror ("ptrace sys 1");
	      break;

	    case SIGSTOP:
	      if (ptrace ((enum __ptrace_request) PTRACE_SYSCALL,
			  traced_process, NULL, NULL) == -1)
		perror ("ptrace sys 3");
	      break;

	    default:		////SIGPIPE
	      if (ptrace ((enum __ptrace_request) PTRACE_SYSCALL,
			  traced_process, NULL, sig) == -1)
		perror ("ptrace sys 2");
	    }
	}
      else			///detach
	{
	  if (ptrace
	      ((enum __ptrace_request) PTRACE_DETACH, traced_process,
	       NULL, NULL) == -1)
	    perror ("ptrace detach");
	  else
	    {
	      tracing = FALSE;

	      if (detach_flag == 1)
		{
		  gtk_entry_set_text (GTK_ENTRY (entry_status), "Detached");
		  gtk_text_buffer_set_text (text_buf, "", -1);
		  gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON
						(button_attach), FALSE);
		}
	      else if (detach_flag == 2)
		{
		  gtk_main_quit ();
		}
	    }
	}
    }
}

//----------------------------------------------------------------------
extern pid_t traced_process;
extern int signal_pipe[2];

void
pipe_signals (int signal)
{
  if (write (signal_pipe[1], &signal, sizeof (int)) != sizeof (int))
    {
      fprintf (stderr, "unix signal %d lost\n", signal);
    }
}

gboolean
handle_io_signal (GIOChannel * source, GIOCondition cond, gpointer d)
{
  GError *error = NULL;		/* for error handling */
  union
  {
    gchar chars[sizeof (int)];
    int signal;
  } buf;
  GIOStatus status;		/* save the reading status */
  gsize bytes_read;		/* save the number of chars read */
  int waitstat;
  int waitresult;
  while ((status = g_io_channel_read_chars (source, buf.chars,
					    sizeof (int), &bytes_read,
					    &error)) == G_IO_STATUS_NORMAL)
    {
      g_assert (error == NULL);	/* no error if reading returns normal */
      if (bytes_read != sizeof (int))
	{
	  fprintf (stderr,
		   "lost data in signal pipe (expected %d, received %d)\n",
		   sizeof (int), bytes_read);
	  continue;		/* discard the garbage and keep fingers crossed */
	}
      /////////////
      while (1)
	{
	  if ((waitresult =
	       waitpid (WAIT_ANY, &waitstat, WNOHANG | WUNTRACED)) <= 0)
	    break;
	  processSignal (waitresult, waitstat, traced_process);
	}
      /////////////
    }
  if (error != NULL)
    {
      fprintf (stderr, "reading signal pipe failed: %s\n", error->message);
      exit (1);
    }
  if (status == G_IO_STATUS_EOF)
    {
      fprintf (stderr, "signal pipe has been closed\n");
      exit (1);
    }

  g_assert (status == G_IO_STATUS_AGAIN);
  return (TRUE);		/* keep the event source */
}
